const http = require('http');
const fs = require('fs');
const path = require('path');


var domain = require('domain');  //错误处理
/**---------------基础函数----------------------**/
	const apiObj = {}
	function api(url,fn){
		apiObj[url] = fn
	}

	// 开启一个服务
	http.createServer((req, res) => {
		res.setHeader("Access-Control-Allow-Origin", "*");
	    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
	    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	    // res.setHeader("Content-Type", "application/json;charset=utf-8");
	    // res.setHeader('content-type','text/html;charset=utf-8')

	    var url = req.url.split('?')[0];
	    var fn = apiObj[url];
	    var d = domain.create();
	    if(fn){
	    	d.run(function() {
	    		fn(req, res)
	    	})
			d.once('error', function(err) {   //捕获错误
				console.log('错误：',err)
			});	    	
	    }else{
		    try{
		        var path = req.url == '/' ? '/index.html' : url;
		        var fileContent = fs.readFileSync(__dirname + path,'binary');
		        res.write(fileContent,'binary')
		    }catch(e){
		        res.writeHead(404,'not found')
		    }
		    res.end()
	    }
	}).listen(3000);

console.log('开启服务： http://localhost:3000');
/**------------------end-----------------------**/
var num = 1;

//修改内容提交保存接口
api('/edit',(req,res)=>{
	var data = '';
	req.on('data',function(chunk){
		data += chunk.toString();
	})	
	req.on('end',function(){
		var obj = JSON.parse(data);
		var text = `$.jsname__`+obj.name+" =`" + obj.con + "`";
		let file = path.resolve(__dirname, 'dist/lunyu/'+obj.name+'.js');	

		//重写之前先备份
		var date = new Date();
    	var Y = date.getFullYear() + '-';
    	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + '_';
        var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + '-';
        var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + '-';
        var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
        var fileName = 'lunyu__'+Y+M+D+h+m+s+'.js';
		var destPath = path.resolve(__dirname, "dist/huishouzhan/"+fileName);
		//移动文件到 huishouzhan 留存
		fs.rename(file, destPath, function (err) {
		  if (err){

		  	console.log('stats:移动文件失败！ ');
		  }
		  	//写入文件
			// fs.writeFile(file, JSON.stringify(data, null, 4), { encoding: 'utf8' }, err => {})
			fs.writeFile(file, text, { encoding: 'utf8' }, err => {
				if(err){
					res.end(JSON.stringify({ msg: 'error' }));
					console.log('stats:写入失败！ ');
				}else{
					res.end(JSON.stringify({ msg: 'ok' }));
					console.log('stats:ok '+num);
					num++;
				}	
			});			  	
		  
		});
	})


});